<?php
/*
* +----------------------------------------------------------------------
* | SF 综合验证授权系统
* +----------------------------------------------------------------------
* | Quotes [ 花开的再灿烂，也有凋谢的一天，致我们过去的青春 ]
* +----------------------------------------------------------------------
* | Author: 陌上花开 <2129876388@qq.com>
* +----------------------------------------------------------------------
* | Date: 2022年1月19日 18:48:32
* +----------------------------------------------------------------------
*/
namespace app\common\controller;

use app\BaseController;
use think\exception\HttpResponseException;
use think\facade\View;
use app\admin\model\PayModel;

/**
 * 基类控制器
 *
 * @author 陌上花开
 * @since 2022-01-21
 */
class CommonBase extends BaseController
{

    /**
     * 初始化方法
     */
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub

        // 初始化请求配置
        $this->initRequestConfig();
        // 检测安装
        if(!$this->isInstall()){
            if(!preg_match('/install/', app_path())){
                $this->redirectTo('/install.php/index');
            }
        }else {
            // 初始化配置
            $this->initConfig();
        }
    }

    /**
     * 初始化请求配置
     */
    public function initRequestConfig()
    {
        // 定义是否GET请求
        defined('IS_GET') or define('IS_GET', $this->request->isGet());

        // 定义是否POST请求
        defined('IS_POST') or define('IS_POST', $this->request->isPost());

        // 定义是否AJAX请求
        defined('IS_AJAX') or define('IS_AJAX', $this->request->isAjax());

        // 定义是否PAJAX请求
        defined('IS_PJAX') or define('IS_PJAX', $this->request->isPjax());

        // 定义是否PUT请求
        defined('IS_PUT') or define('IS_PUT', $this->request->isPut());

        // 定义是否DELETE请求
        defined('IS_DELETE') or define('IS_DELETE', $this->request->isDelete());

        // 定义是否HEAD请求
        defined('IS_HEAD') or define('IS_HEAD', $this->request->isHead());

        // 定义是否PATCH请求
        defined('IS_PATCH') or define('IS_PATCH', $this->request->isPatch());

        // 定义是否为手机访问
        defined('IS_MOBILE') or define('IS_MOBILE', $this->request->isMobile());

        // 定义是否为cli
        defined('IS_CLI') or define('IS_CLI', $this->request->isCli());

        // 定义是否为cgi
        defined('IS_CGI') or define('IS_CGI', $this->request->isCgi());

        // 控制器名称
        $controller_name = $this->request->controller();
        // 操作方法名称
        $action_name = $this->request->action();
        // 定义控制器名
        defined('CONTROLLER_NAME') or define('CONTROLLER_NAME', $controller_name);
        // 定义操作方法名
        defined('ACTION_NAME') or define('ACTION_NAME', $action_name);

        View::assign("app", strtolower($controller_name));
        View::assign("act", strtolower($action_name));
    }

    /**
     * 检测安装
     * @author 陌上花开
     * @since: 2022/01/19
     */
    public function isInstall()
    {
        if(!file_exists(APP_PATH . DS . 'install' . DS . 'SF_Auth.Lock')){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 初始化配置
     * @author 陌上花开
     * @since: 2022/01/19
     */
    public function initConfig()
    {
        // 系统全称
        View::assign("title", !empty(conf('title'))?conf('title'):'SF授权平台');
        View::assign("keywords", !empty(conf('keywords'))?conf('keywords'):'SF授权平台');
        View::assign("description", !empty(conf('description'))?conf('description'):'SF授权平台');
        View::assign("foot", !empty(conf('foot'))?conf('foot'):'Copyright © SF-陌上花开');
        View::assign("ICP", !empty(conf('ICP'))?conf('ICP'):'');
        // 系统简称
        View::assign("year", date('Y'));
        // 系统版本
        View::assign("domain", SITE_URL);

        // 请求参数
        $this->param = $this->request->param();

        // 分页基础默认值
        defined('PERPAGE') or define('PERPAGE', isset($this->param['limit']) ? $this->param['limit'] : 20);
        defined('PAGE') or define('PAGE', isset($this->param['page']) ? $this->param['page'] : 1);
    }

    /**
     * JSON返回结果
     * @author 陌上花开
     * @date 2022-01-21
     */
    public function jsonReturn()
    {
        false && message();

        // 获取参数
        $arr = func_get_args();

        if (!is_array($arr[0])) {
            // 回调函数
            $result = call_user_func_array("message", $arr);
        } else {
            // 函数模式
            $result = $arr[0];
        }
        // 格式化数组
        $result = $this->getStringArray($result);

        // 返回结果
        $output = json_encode($result);
        echo $output;
        exit();
    }

    public function createOrder(){
        if(IS_POST){
            $post = request()->post();
            $type = !empty($post['type'])?$post['type']:null;
            if(empty($type)) return message('创建订单失败！[errorCode:CreateOrderTypeEmpty]', false);
            $payModel = new PayModel();
            switch ($type){
                case 'recharge':
                    $money = !empty($post['money'])?$post['money']:null;
                    if(empty($money)) return message('所充值的金额格式错误！[errorCode:RechargeMoneyError]', false);
                    if($money == 'diy'){
                        $money = !empty($post['diy'])?$post['diy']:null;
                        if(empty($money)) return message('所充值的金额格式错误！[errorCode:RechargeMoneyError]', false);
                        $money = round($money, 2);
                    }else{
                        $money = round($money, 2);
                    }

                    $name = '充值余额 - '. $money .'元';
                    $data = [
                        'buy_type' => 'recharge',
                        'name' => $name,
                        'userid' => cookie('userId'),
                        'money' => $money,
                    ];
                    return $payModel->edit($data);
                default:
                    return message('创建订单失败！[errorCode:CreateOrderTypeError]', false);
            }
        }
    }

    /**
     * 格式化字符串
     * @param $array
     * @return mixed
     * @author 陌上花开
     * @date 2022-01-21
     */
    private function getStringArray($array)
    {
        foreach ($array as $key => $row) {
            if (is_array($row)) {
                $array[$key] = $this->getStringArray($row);
            } elseif (is_object($row)) {
                //TODO...
            } else {
                $array[$key] = (string)$row;
            }
        }
        return $array;
    }

    /**
     * 自定义重定向方法
     * @param $args
     */
    public function redirectTo(...$args){
        // 此处 throw new HttpResponseException 这个异常一定要写
        throw new HttpResponseException(redirect(...$args));
    }
    /**
     * 空操作捕捉
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/19
     */
    public function _empty(){
        return $this->render("public/403");
    }

    public function __call($method, $args){
        return $this->_empty();
    }

    /**
     * 模板渲染
     * @param string $tpl 模板地址
     * @param array $data 参数
     * @return mixed
     * @author 陌上花开
     * @date 2022/1/25
     */
    public function render($tpl = "", $data = [])
    {
        return View::fetch($tpl, $data);
    }

}